package com.wj.taobaoke;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.wj.taobaoke.nvzhuang.NvZhuangGuanJianZi;

/**
 * 自动生成新闻
 * 模板中有:<!-- nav --><!--1-->三个特殊的代码段
 * <!--1-->为index页面
 * <!-- nav -->为子页面
 * @author wangjun
 *
 */
public class GenerateBlogFile {
	
	private ReadTemplate readTemplate;
	public static List<BlogItem> allItemList = new ArrayList<BlogItem>();
	
	public GenerateBlogFile(ReadTemplate readTemplate){
		this.readTemplate = readTemplate;
	}
	
	public static ThreadPoolExecutor executor = new ThreadPoolExecutor(
			10,	//指的是保留的线程池大小
			10, //最大线程池， 指的是线程池的最大大小
			3, 	//指的是空闲线程结束的超时时间
			TimeUnit.SECONDS, 	//表示 keepAliveTime 的单位
			new LinkedBlockingQueue<Runnable>(),
			new ThreadPoolExecutor.DiscardPolicy() //直接放弃当前任务
			);
	/** 使用百度的搜索列表进行生成 */
	public void generatgeBaiduNewsList(GuanJianZi guanJianZi){
		AnalysistBaiduNew analysistBaiduNew = new AnalysistBaiduNew();
		List<BlogItem> blogItems = analysistBaiduNew.analysisBlogItemsList(guanJianZi.baiduNewsUrl);
		for (int i = 0; i < blogItems.size(); i++) {
			executor.execute(new GenerateBlogItemHtmlFile(blogItems.get(i), guanJianZi, readTemplate));
		}
		createIndexHtmlFile(blogItems, guanJianZi);
	}
	
	
	/** 创建首页 */
	public void createIndexHtmlFile(List<BlogItem> blogItems, GuanJianZi guanJianZi){
		File pathFile = new File(guanJianZi.getBlogFilePath());
		if(!pathFile.exists()){
			pathFile.mkdir();
		}
		FileWriter fileWriter = null;
		try{
			fileWriter = new FileWriter(guanJianZi.getBlogFilePath()+"index.html");
			for(String string : readTemplate.templateStrList){
				if("<!--news flag-->".equals(string)){
					for(String newsString : readTemplate.newsListStrList){
						 if("<!-- news -->".equals(newsString)){
							for (int i = 0; i < blogItems.size(); i++) {
								fileWriter.write(generageBlogItemStr(blogItems.get(i), guanJianZi).toString());
								fileWriter.write("\r\n");
								fileWriter.flush();
							}
						 }else{
							fileWriter.write(newsString);
							fileWriter.write("\r\n");
						}
					}
				}else{
					string = string.replaceFirst("<title>关键字", "<title>"+guanJianZi.guanJianZi);
					string = string.replaceAll("<meta name=\"keywords\" content=\"关键字\"", "<meta name=\"keywords\" content=\""+guanJianZi.guanJianZi+"\"");
					string = string.replaceAll("<meta name=\"description\" content=\"关键字\"", "<meta name=\"description\" content=\"想了解"+guanJianZi.guanJianZi+"的最新资讯？那跟我来吧，在这里，你会有新发现。\"");

					fileWriter.write(string);
					fileWriter.write("\r\n");
				 }
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(fileWriter != null){
				try{
					fileWriter.flush();
					fileWriter.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}

	/** 创建一个条目的html */
	private StringBuilder generageBlogItemStr(BlogItem blogItem, GuanJianZi guanJianZi){
		String blogUrl = guanJianZi.guanJianZiBlogUrl+blogItem.index+".html";
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("<li>");
		stringBuilder.append("<div class=\"list_top clearfix\">");
		stringBuilder.append("<span class=\"wzb\"><a title=\"").append(blogItem.hiddenTitle)
			.append("\" target=\"_blank\" href=\"").append(blogUrl).append("\">")
			.append(blogItem.index).append(".&nbsp;").append(blogItem.title).append("</a></span>");
		stringBuilder.append("<span class=\"time\">").append(blogItem.createTime).append("</span></div>");
		stringBuilder.append("<div class=\"subtitle\">").append(blogItem.content).append("<span><a title=\"")
			.append(blogItem.hiddenTitle).append("\" href=\"").append(blogUrl)
			.append("\" class=\"orange\" target=\"_blank\">[详细]</a></span></div></li>");
		return stringBuilder;
	}

	public static void main(String[] args) {
		BlogItem blogItem = new BlogItem();
		blogItem.index = 17;
		blogItem.contentUrl = "http://www.chinavalue.net/Story/405727.aspx";
		GenerateBlogItemHtmlFile blogItemHtmlFile = new GenerateBlogItemHtmlFile(blogItem, NvZhuangGuanJianZi.XinKuanNvZhuang(), null);
		blogItemHtmlFile.analysisNewsHtml();
	}
}

/**********************************   成生页面      ********************************************/

class GenerateBlogItemHtmlFile implements Runnable{

	private AnalysisWeb analysisWeb;
	private BlogItem blogItem;
	private GuanJianZi guanJianZi;
	private ReadTemplate readTemplate;
	
	
	public GenerateBlogItemHtmlFile(BlogItem blogItem, GuanJianZi guanJianZi, ReadTemplate readTemplate){
		this.blogItem = blogItem;
		this.guanJianZi = guanJianZi;
		this.readTemplate = readTemplate;
	}
	
	@Override
	public void run() {
		generateBlogHtmlFile();
		GenerateBlogFile.allItemList.remove(blogItem);
		System.out.println(guanJianZi.guanJianZi+"_"+blogItem.index+"_success, title="+blogItem.hiddenTitle);
	}
	/** 第一套生成子页面的方案 */
	private boolean generateBlogHtmlFile(){
		FileWriter fileWriter = null;
		 try{
			 fileWriter = new FileWriter(guanJianZi.getBlogFilePath()+blogItem.index+".html");
			 for(String string : readTemplate.templateStrList){
				 if("<!--news flag-->".equals(string)){
					fileWriter.write(string);
					fileWriter.write("\r\n");
					writeNewsHtml(fileWriter);
				 }else if("<!--page navigation flag-->".equals(string)){
					 	for(String navStr : readTemplate.navStrList){
					 		if("<!--page navigation-->".equals(navStr)){
					 			fileWriter.write(guanJianZi.getGuanJianZiNav()+blogItem.hiddenTitle);
					 		}else{
					 			fileWriter.write(navStr);
					 		}
					 	}
			 			fileWriter.write("\r\n");
				}else{
					string = string.replaceFirst("<title>关键字", "<title>"+blogItem.hiddenTitle);
					string = string.replaceAll("<meta name=\"keywords\" content=\"关键字\"", "<meta name=\"keywords\" content=\""+blogItem.hiddenTitle+"\"");
					string = string.replaceAll("<meta name=\"description\" content=\"关键字\"", "<meta name=\"description\" content=\""+blogItem.hiddenTitle+"\"");

					fileWriter.write(string);
					fileWriter.write("\r\n");
				 }
			 }


		 }catch(Exception e){
			 e.printStackTrace();
		 }finally{
			 if(fileWriter != null){
				 try{
					 fileWriter.flush();
					 fileWriter.close();
				 }catch(Exception e){
					 e.printStackTrace();
				 }
			 }
		 }
		 return true;
	}
	private void writeNewsHtml(FileWriter fileWriter) throws IOException{
		 List<String> contentList = analysisNewsHtml();
		 fileWriter.write("<div class=\"left \"><div class=\"brief bgFFFFFF\"><h1>"+blogItem.hiddenTitle+"</h1><div class=\"blogcontent\">");
		 fileWriter.write("<div class=\"info\">来源："+blogItem.createTime+"</div>");
		 fileWriter.write("<div class=\"intro\">"+blogItem.content+"</div>");
		 writeOneGoodsFrameHtml(fileWriter);
		 for (String string : contentList) {
			string = string.replaceAll("<!--(.*?)-->", "");
			string = string.replaceAll("href(.*?)\"(.*?)\"", "href=\""+guanJianZi.guanJianZiBlogUrl+"index.html\"");
			string = string.replaceAll("href(.*?)'(.*?)'", "href=\""+guanJianZi.guanJianZiBlogUrl+"index.html\"");
			if(string.matches("(.*?)<a(.*?)>2</a>(.*?)")){
				break;
			}
			fileWriter.write(string);
		 }
		 fileWriter.write("</div></div></div>");		
	}
	
	private void writeOneGoodsHtml(FileWriter fileWriter) throws IOException{
		fileWriter.write("<a href=\""+guanJianZi.guanJianZiGoodsUrl+"index.html\"><img src=\""+guanJianZi.guanJianZiGoodsUrl+"1.jpg\"></a>");
	}

	private void writeOneGoodsFrameHtml(FileWriter fileWriter) throws IOException{
		fileWriter.write("<p align=\"center\" style=\"text-indent: 3px;\">");
		fileWriter.write("<script type=\"text/javascript\" language=\"javascript\">document.writeln(\"<Iframe src=\\\""+
				guanJianZi.guanJianZiGoodsUrl+"1.html"+
				"\\\" width=\\\"460px\\\" height=\\\"460px\\\" scrolling=\\\"no\\\" frameborder=\\\"0\\\"></Iframe>\");</script>");
		fileWriter.write("</p>");
	}
	
	public List<String> analysisNewsHtml(){
		analysisWeb = new AnalysisWeb();
		String html = analysisWeb.getOneHtml(blogItem.contentUrl, "utf-8", true);
		if(html.length() == 0){
			System.out.println(blogItem.index+":not read html;"+blogItem.contentUrl+";title="+blogItem.hiddenTitle);
			html = analysisWeb.getOneHtml(blogItem.contentUrlBak, "utf-8", true);
		}
		if(html.length() == 0){
			System.out.println(blogItem.index+":not read html;"+blogItem.contentUrlBak+";title="+blogItem.hiddenTitle);
			html = analysisWeb.getOneHtml(blogItem.contentUrlBak, "utf-8", true);
		}
		
		String titleStr = analysisWeb.getTitle(html).trim();
		String titleSubStr = null;
		String[] titleStrArray = titleStr.split("-");
		if(titleStrArray[0].endsWith("网")){
			titleStr = titleStrArray[titleStrArray.length - 1];
		}
		if(titleStr.length() > 8){
			titleSubStr = titleStr.substring(0, 8);
		}else{
			titleSubStr = titleStr;
		}
		
		String temp = getContent(html, titleSubStr);
		if(temp.length() == 0){
			temp = getContent(html, blogItem.hiddenTitle);
		}
		
		List<String> contentList = new ArrayList<String>();		
		List<String> tempList = analysisWeb.getContentListFroRegex(temp, "<\\s*p(.*?)<\\s*/p\\s*>");
		if(tempList.size() == 0){
			tempList = analysisWeb.getContentListFroRegex(temp, "<\\s*div(.*?)<\\s*/div\\s*>");
		}
		if(tempList.size() == 0){
			tempList = analysisWeb.getContentListFroRegex(temp, "<\\s*td(.*?)<\\s*/td\\s*>");
		}
		if(tempList.size() == 0){
			System.out.println(blogItem.index+": not find <div> or <p> or <td>;"+blogItem.contentUrl+";title="+titleSubStr);
		}
		for (String string : tempList) {
			String onetemp = string.replaceAll("(?i)<\\s*div(.*?)>", "");
			onetemp = onetemp.replaceAll("(?i)<\\s*/div\\s*>", "");
			onetemp = onetemp.replaceAll("(?i)<\\s*span(.*?)>", "");
			onetemp = onetemp.replaceAll("(?i)<\\s*/span\\s*>", "");
			onetemp = onetemp.replaceAll("(?i)<\\s*table(.*?)>", "");
			onetemp = onetemp.replaceAll("(?i)<\\s*/table\\s*>", "");
			onetemp = onetemp.replaceAll("(?i)<\\s*td(.*?)>", "");
			onetemp = onetemp.replaceAll("(?i)<\\s*/td\\s*>", "");
			onetemp = onetemp.replaceAll("(?i)<\\s*tr(.*?)>", "");
			onetemp = onetemp.replaceAll("(?i)<\\s*/tr\\s*>", "");
			onetemp = onetemp.replaceAll("(?i)<\\s*iframe(.*?)>", "");
			onetemp = onetemp.replaceAll("(?i)<\\s*/iframe\\s*>", "");
			onetemp = onetemp.replaceAll("(?i)<\\s*img(.*?)>", "");
			onetemp = onetemp.replaceAll("(?i)<\\s*a(.*?)><\\s*/a\\s*>", "");
			onetemp = onetemp.replaceAll("<!--(.*?)-->", "");
			onetemp = onetemp.replaceAll("(?i)<\\s*script(.*?)<\\s*/script\\s*>", "").trim();
			if(onetemp.length() == 0){
				continue;
			}
			if(onetemp.contains("来源:") || onetemp.contains("来源：")){
				continue;
			}
			if(onetemp.contains("&gt;") && onetemp.contains("正文")){
				continue;
			}
			contentList.add("<p>"+onetemp+"</p>");
			if(onetemp.matches("(.*?)<\\s*a(.*?)>\\s*2\\s*<\\s*/a\\s*>(.*?)")){
				break;
			}
			if(contentList.size() > 5){
				break;
			}
		}
		 
		return contentList;
	}
	

	private String getContent(String html, String titleSubStr){
		titleSubStr = titleSubStr.replace("(", ".?");
		titleSubStr = titleSubStr.replace(")", ".?");
		titleSubStr = titleSubStr.replace(":", ".?");
		titleSubStr = titleSubStr.replace("：", ".?");
		titleSubStr = titleSubStr.replace("“", ".?");
		titleSubStr = titleSubStr.replace("”", ".?");
		titleSubStr = titleSubStr.replace("[", ".?");
		titleSubStr = titleSubStr.replace("]", ".?");
		titleSubStr = titleSubStr.replace("?", ".?");
		int headIndex = html.indexOf("</head>");
		if(headIndex < 0){
			headIndex = html.indexOf("</HEAD>");
		}
		if(headIndex < 0){
			System.out.println(blogItem.index+": not find </head>" +blogItem.contentUrl+";title="+titleSubStr);
			headIndex = 0;
		}
		String bodyTemp = html.substring(headIndex);
		String temp = analysisWeb.getForRegex(bodyTemp, "<\\s*h1([^>]*?)>"+titleSubStr+"(.*?)<\\s*/body\\s*>").trim();
		if(temp.length() == 0){
			temp = analysisWeb.getForRegex(bodyTemp, "<\\s*h2([^>]*?)>"+titleSubStr+"(.*?)<\\s*/body\\s*>").trim();
		}
		if(temp.length() == 0){
			temp = analysisWeb.getForRegex(bodyTemp, "<\\s*h3([^>]*?)>"+titleSubStr+"(.*?)<\\s*/body\\s*>").trim();
		}
		if(temp.length() == 0){
			temp = analysisWeb.getForRegex(bodyTemp, titleSubStr+"(.*?)<\\s*/body\\s*>").trim();
		}
		if(temp.length() == 0){
			System.out.println(blogItem.index+":not find blog contnet;url="+blogItem.contentUrl+";title="+titleSubStr);
		}
		if(temp.length() > 0 && temp.matches("(.*?)<\\s*a(.*?)>2<\\s*/a\\s*>(.*?)")){
			String tempend = analysisWeb.getForRegex(temp, titleSubStr+"(.*?)<\\s*a(.*?)>2<\\s*/a\\s*>");
			if(tempend.length() != 0){
				temp = tempend;
			}
		}
		return temp;
	}
	
}